var util = require('../../utils/util.js');
const md = require('../../utils/md5.js');
const app = getApp();
const post = require('../../utils/post.js');
var count = 0;
var loop = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: '2018-04-13',
    date2: '2018-04-13',
    date3: '2018-04-13',
    choose: 1,
    active: 0,
    pageindex: 1,
    pageszie: 20,
    srctype: "筛选",
    showtype: "筛选",
    maintype: app.server.assettype,
    znmaintype: app.server.znassettype,
    hide: 1,
    time1:'00:00',
    time2:'23:59'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.socket();
    var that = this;
    var time = util.formatTime(new Date());
    var timearr = time.split(' ')[0];
    // 再通过setData更改Page()里面的data，动态更新页面的数据  
    var shoparray = [{
      "name": "所有往来商户",
      "toaccid": "All"
    }];
    var isvendor = wx.getStorageSync('newinfo').IsVendor;

    this.setData({
      date: timearr,
      date2: timearr,
      date3: timearr,
      shoparray: shoparray,
      shopindex: 0,
      showtype: timearr,
      shopshow: "所有往来商户",
      toaccid: "all",
      isvendor: isvendor
    });
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight - 120
        })
      },
    })
    that.chushi();
    that.trantype();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var interval = setInterval(function() {
      wx.sendSocketMessage({
        data: [1]
      })
      console.log('发送了一个消息' + loop)
      // count++;
      // if (loop == 0) {
      //   return;
      // }
      // if (count == 20) {
      //   return;
      // }
    }, 10000)
    this.setData({
      dingshi: interval
    })
  },
  socket: function() {
    var that = this;
    wx.connectSocket({
      url: 'wss://api3.zokoo.com.cn/MsgBroker/paynotice_' + wx.getStorageSync('depid') + "?id=wallet_" + wx.getStorageSync('mebid')
    })
    wx.onSocketOpen(function(res) {
      console.log('WebSocket连接已打开！');
      that.setData({
        isconnet: 1
      })
    })
    wx.onSocketError(function(res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    wx.onSocketClose(function(res) {
      console.log('WebSocket 已关闭！')
    })
    wx.onSocketMessage(function(res) {
      console.log(res)
      if (res.data) {
        var data = res.data;
        // console.log(data)
        data = JSON.parse(data);
        data = JSON.parse(data);
        console.log(data)
        if (data) {
          console.log(data.money)
          var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text=众库到账" + data.money + "元";
          url = encodeURI(url);
          that.playaudio(url);
          that.chushi();
        }
      }

    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  onUnload: function() {
    this.setData({
      hide: 0
    })
    loop = 0;
    clearInterval(this.data.dingshi)
    wx.closeSocket();
  },
  getkey: function(e) {
    this.setData({
      key: e.detail.value
    })
  },
  chushi: function() {
    var that = this;
    // 获取时间戳
    var apinameIsMeb = "/BO/TR_Detail/Query";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    var where = "AccID = " + wx.getStorageSync('depid') + " and AccDate >= '" + that.data.date + " 00:00:00' and AccDate <= '" + that.data.date + " 23:59:59' ";
    console.log(where);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        pageindex: 1,
        pagesize: 20,
        summary: 1,
        where: where
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 0) {
          var data = [];
          for (var i = 0; i < res.data.data.length; i++) {
            data[i] = res.data.data[i];
            // data[i]['AccDate'] = res.data.data[i].AccDate.split('T')[0];
            // data[i]['AccDate'] = res.data.data[i].AccDate.split(' ')[0];
            data[i]['AccDate'] = (data[i]['AccDate']).replace(/-/g, '.');
            // data[i]['AccDate'] = res.data.data[i].AccDate.substring(0, res.data.data[i].AccDate.length - 7);

          }
          that.setData({
            dayinfo: data,
            moneyget: res.data.summary.MnyGet - (res.data.summary.ChargeGet ? res.data.summary.ChargeGet:0),
            moneypay: res.data.summary.MnyPay,
          })
          that.jieyu(that.data.date2, that.data.date3);
          that.getshoparr(that.data.date, that.data.date)
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          return;
        }
      }
    })
  },
  //第一个已弃用
  bindDateChange: function(e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      date: e.detail.value
    });
    return;
    // return;
    // 获取时间戳
    var date = that.data.date;
    var srctype = that.data.srctype;
    var where = "AccID = " + wx.getStorageSync('depid') + " and AccDate >= '" + date + " 00:00:00' and AccDate <= '" + date + " 23:59:59' ";
    if (srctype != "all" && srctype != "筛选") {
      if (srctype == "在途") {
        where = where + "and ToAccOver = 0";
      } else {
        where = where + " and Trantype like '%" + srctype + "%'";
      }
    }
    console.log(where);
    var apinameIsMeb = "/BO/TR_Detail/Query";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        pageindex: 1,
        pagesize: 20,
        summary: 1,
        where: where
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 0) {
          var data = [];
          console.log(res.data.data.length);
          if (res.data.data.length > 0) {
            for (var i = 0; i < res.data.data.length; i++) {
              data[i] = res.data.data[i];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split('T')[0];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split(' ')[0];
              data[i]['AccDate'] = (data[i]['AccDate']).replace(/-/g, '.');
              // data[i]['AccDate'] = res.data.data[i].AccDate.substring(0, res.data.data[i].AccDate.length - 7);
              // data[i]['AccDate'] = (data[i]['AccDate']).replace("T", ' ');
              // data[i]['ToAccDate'] = res.data.data[i].ToAccDate.substring(res.data.data[i].ToAccDate.length - 7);
              // data[i]['ToAccDate'] = (data[i]['ToAccDate']).replace("T", ' ');
            }
            that.setData({
              moneyget: res.data.summary.MnyGet,
              moneypay: res.data.summary.MnyPay,
            })
          } else {
            that.setData({
              moneyget: 0,
              moneypay: 0,
            })
          }

          that.setData({
            dayinfo: data,
            pageindex: 1,
          })
          that.jieyu(date);
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          return;
        }
      }
    })

  },
  bindDateChange2: function(e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      date2: e.detail.value
    });

  },
  bindDateChange3: function(e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      date3: e.detail.value
    });
  },
  bindTimeChange:function(e){
    this.setData({
      time1: e.detail.value
    });
  },
  bindTimeChange2: function (e) {
    this.setData({
      time2: e.detail.value
    });
  },
  bindShopChange: function(e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var shopshow = that.data.shoparray[e.detail.value].name;
    if (shopshow.length > 8) {
      shopshow = shopshow.substring(0, 8) + "...";
    }
    that.setData({
      shopindex: e.detail.value,
      shopshow: shopshow,
      toaccid: that.data.shoparray[e.detail.value].toaccid
    });
    var that = this;
    var date2 = that.data.date2;
    var date3 = that.data.date3;
    var srctype = that.data.srctype;
    that.search(date2, date3, srctype);
    that.setData({
      choose: 1
    })
  },
  choosetype: function() {
    this.setData({
      choose: 0
    })
  },
  betype: function(e) {
    // console.log(e);
    var that = this;
    that.setData({
      active: e.currentTarget.dataset.active,
      // choose: 1,
      srctype: e.currentTarget.dataset.type,
      showtype: e.currentTarget.dataset.name
    });
    return;
    var date = that.data.date;
    var srctype = e.currentTarget.dataset.type;
    var where = "AccID = " + wx.getStorageSync('depid') + " and AccDate >= '" + date + " 00:00:00' and AccDate <= '" + date + " 23:59:59' ";
    if (srctype != "all") {
      if (srctype == "在途") {
        where = where + "and ToAccOver = 0";
      } else {
        where = where + " and Trantype like '%" + srctype + "%'";
      }
    }

    console.log(where);
    // 获取时间戳
    var apinameIsMeb = "/BO/TR_Detail/Query";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        pageindex: 1,
        pagesize: 20,
        summary: 1,
        where: where
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 0) {
          var data = [];
          console.log(res.data.data.length);
          if (res.data.data.length > 0) {
            for (var i = 0; i < res.data.data.length; i++) {
              data[i] = res.data.data[i];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split('T')[0];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split(' ')[0];
              data[i]['AccDate'] = (data[i]['AccDate']).replace(/-/g, '.');
              // data[i]['AccDate'] = res.data.data[i].AccDate.substring(0, res.data.data[i].AccDate.length - 7);
              // data[i]['AccDate'] = (data[i]['AccDate']).replace("T", ' ');
              // data[i]['ToAccDate'] = res.data.data[i].ToAccDate.substring(res.data.data[i].ToAccDate.length - 7);
              // data[i]['ToAccDate'] = (data[i]['ToAccDate']).replace("T", ' ');
            }
            that.setData({
              moneyget: res.data.summary.MnyGet,
              moneypay: res.data.summary.MnyPay,
            })
          } else {
            that.setData({
              moneyget: 0,
              moneypay: 0,
            })
          }

          that.setData({
            dayinfo: data,
            pageindex: 1,
          })
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          return;
        }
      }
    })
  },

  closemodel: function() {
    this.setData({
      choose: 1
    })
  },
  cancer: function() {
    this.setData({
      choose: 1
    })
  },
  reset: function() {
    var that = this;
    var time = util.formatTime(new Date());
    var timearr = time.split(' ')[0];
    // 再通过setData更改Page()里面的data，动态更新页面的数据  
    this.setData({
      date2: timearr,
      date3: timearr,
      key: '',
      choose: 1,
      toaccid: "all"
    });
    that.search(timearr, timearr, 'all')
  },
  makesure: function() {
    var that = this;
    var date2 = that.data.date2;
    var date3 = that.data.date3;
    var srctype = that.data.srctype;
    that.search(date2, date3, srctype);
    that.getshoparr(date2, date3)
    that.setData({
      choose: 1,
      showtype:'筛选'
    })
  },
  tomonth: function() {
    this.setData({
      hide: 0
    })
    wx.navigateTo({
      url: '/pages/monthcount/monthcount?mebid=' + wx.getStorageSync('depid'),
    })
  },
  tobill: function(e) {
    var id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: '/pages/billdetail/billdetail?id=' + id,
    })
  },
  jieyu: function(begin, end) {
    var that = this;
    var datas = {};
    datas.where = "AccID =" + wx.getStorageSync('depid') + " and AccDate >= '" + begin + " 00:00:00' and AccDate <= '" + end + " 23:59:59' ";
    var datacall = function(res) {
      console.log(res);
      if (res.data.data.length != 0) {
        var jieyu = 0.00;
        if (res.data.data.length == 2) {
          jieyu = res.data.data[1].Balance
        } else {
          jieyu = res.data.data[0].Balance
        }
        that.setData({
          jieyu: jieyu
        })
      }
    }
    var res2 = post.getdata("/BO/TR_DayBalance/Query", datas, datacall);
  },
  trantype: function() {
    var that = this;
    var datas = {};
    var datacall = function(res) {
      console.log(res);
      if (res.data.data.length != 0) {
        var typedata = [{
          "TranName": "全部",
          "TranType": "all"
        }];
        for (var i = 1; i <= res.data.data.length; i++) {
          typedata[i] = res.data.data[i - 1];
        }
        that.setData({
          trantype: typedata
        })
      }
    }
    var res2 = post.getdata("/BO/TR_TranType/Query", datas, datacall);
  },
  getshoparr: function(begin, end) {
    var that = this;
    var isvendor = that.data.isvendor;
    if (!isvendor) {
      return;
    }
    var data = {};
    data.AccID = wx.getStorageSync('depid');
    data.Begin = begin + " 00:00:00";
    data.End = end + " 23:59:59";
    var datacall = function(res) {
      console.log(res);
      if (res.data.data.length != 0) {
        var shoparray = [{
          "name": "所有往来商户",
          "toaccid": "all"
        }];
        var ii = {};
        for (var i = 0; i < res.data.data.length; i++) {
          ii.name = res.data.data[i].AccName;
          ii.toaccid = res.data.data[i].AccID;
          shoparray[i + 1] = ii;
          ii = {};
        }
        that.setData({
          shoparray: shoparray,
          shopshow: "所有往来商户",
          toaccid: "all"
        })
      } else {
        that.setData({
          shoparray: [{
            "name": "所有往来商户",
            "toaccid": "all"
          }]
        })
      }
    }
    var res2 = post.getdata("/BO/V_Dealings/Query", data, datacall);
  },
  search: function(begin, end, types = 'all', pageindex = 1) {
    var that = this;
    var datas = {};
    var key = that.data.key;
    var toaccid = that.data.toaccid;
    let timestrat = " " + that.data.time1 + ":00";
    let timeend = " " + that.data.time2 + ":59";
    var where = "AccID =" + wx.getStorageSync('depid') + " and AccDate >= '" + begin + timestrat + "' and AccDate <= '" + end + timeend+"'";
    if (types != 'all' && types != "筛选") {
      if (types == "在途") {
        where = where + "and ToAccOver = 0";
      } else {
        where = where + " and Trantype like '%" + types + "%'";
      }
    }
    if (key) {
      where = where + " and (ToMebName like '%" + key + "%' or ToAccName like '%" + key + "%')";
    }
    if (toaccid && toaccid != 'all') {
      where = where + " and ToAccID = " + toaccid;
    }
    datas.where = where;
    console.log(where);
    datas.pageindex = pageindex;
    datas.pagesize = 20;
    datas.summary = 1;
    var datacall = function(res) {
      console.log(res);
      if (res.data.code == 0) {
        var data = [];
        console.log(res.data.data.length);
        if (res.data.data.length > 0) {
          for (var i = 0; i < res.data.data.length; i++) {
            data[i] = res.data.data[i];
            data[i]['AccDate'] = (data[i]['AccDate']).replace(/-/g, '.');
          }
          that.setData({
            moneyget: res.data.summary.MnyGet,
            moneypay: res.data.summary.MnyPay,
          })
        } else {
          that.setData({
            moneyget: 0,
            moneypay: 0,
          })
        }

        that.setData({
          dayinfo: data,
          pageindex: 1,
        })
        that.jieyu(begin, end);
      }
    }
    var res2 = post.getdata("/BO/TR_Detail/Query", datas, datacall);
  },
  newdata: function() {
    wx.showLoading({
      title: '正在加载...',
    })
    var that = this;
    var date2 = that.data.date2;
    var date3 = that.data.date3;
    var srctype = that.data.srctype;
    var toaccid = that.data.toaccid;
    var key = that.data.key;
    let timestrat = " " + that.data.time1 + ":00";
    let timeend = " " + that.data.time2 + ":59";
    var where = "AccID = " + wx.getStorageSync('depid') + " and AccDate >= '" + date2 + timestrat + "' and AccDate <= '" + date3 + timeend+"'";
    if (srctype != "all" && srctype != "筛选") {
      if (srctype == "在途") {
        where = where + "and ToAccOver = 0";
      } else {
        where = where + " and Trantype like '%" + srctype + "%'";
      }
    }
    if (toaccid && toaccid != 'all') {
      where = where + " and ToAccID = " + toaccid;
    }
    if (key) {
      where = where + " and (ToMebName like '%" + key + "%' or ToAccName like '%" + key + "%')";
    }
    console.log(where);
    var apinameIsMeb = "/BO/TR_Detail/Query";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        pageindex: that.data.pageindex + 1,
        pagesize: 20,
        summary: 1,
        where: where
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        
        console.log(res);
        if (res.data.code == 0) {
          var data = [];
          console.log(res.data.data.length);
          var dayinfo = that.data.dayinfo;
          if (res.data.data.length > 0) {
            for (var i = 0; i < res.data.data.length; i++) {
              data[i] = res.data.data[i];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split('T')[0];
              // data[i]['AccDate'] = res.data.data[i].AccDate.split(' ')[0];
              data[i]['AccDate'] = (data[i]['AccDate']).replace(/-/g, '.');
              dayinfo.push(res.data.data[i]);
            }
          }

          that.setData({
            dayinfo: dayinfo,
            pageindex: that.data.pageindex + 1
          })
          // that.jieyu(date2,date3);
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          // return;
        }
        setTimeout(function(){
          wx.hideLoading();
        },1500);
        return;
      }
    })
  },
  getmq: function() {
    var that = this;
    if (that.data.hide != 1) {
      return;
    }
    var depid = wx.getStorageSync('depid');
    var datas = {};
    datas.Key = "zkwallet/acc/" + depid;
    var datacall = function(res) {
      console.log(res);
      if (res.data.data) {
        that.chushi();
        var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text=众库到账" + res.data.data.Money + "元";
        url = encodeURI(url);
        that.playaudio(url);
        that.getmq();
      } else {
        that.getmq();
      }
    }
    var res2 = post.getdata("/System/GetMessages", datas, datacall);
  },
  playaudio: function(url = '') {

    console.log(1);
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = url;
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  }
})